#!/bin/sh -e

PREREQS=""

prereqs() { echo "$PREREQS"; }

case "$1" in
    prereqs)
    prereqs
    exit 0
    ;;
esac


ROOTFS_MOUNT=$(cat /proc/mounts | grep ${ROOT} | grep ${rootmnt})
ROOTFS_OPTIONS=$(echo $ROOTFS_MOUNT | awk '{ print $4 }')
ROOTFS_FSTYPE=$(echo $ROOTFS_MOUNT | awk '{ print $3 }')
ROOTFS_DEVICE=${ROOT}

export ROOTFS_DEVICE

SHOW_SERIAL_NO="y"
export SHOW_SERIAL_NO

CODE_NO_HYPHEN="y"
export CODE_NO_HYPHEN

SIGFILE="/etc/LICENSE"
KYINFO="/etc/.kyinfo"
KYACTIVATION="/etc/.kyactivation"


stay_message() {
	msg="${1}"

	echo ""
	echo $msg
	while true
	do
		sleep 100
	done
}

ky_activate_retry() {
	if [ $1 = 1 ]; then
		stay_message "麒麟信息文件有误"
	elif [ $1 = 2 ]; then
		echo "请重试："
		read  KY_ACT_CODE
		kylin_activate_i ${rootmnt}$SIGFILE ${rootmnt}$KYACTIVATION ${rootmnt}$KYINFO "$KY_ACT_CODE"  || ky_activate_retry $?
	fi

}

ky_activate() {
	echo ""
	echo "请输入激活码"
	read  KY_ACT_CODE
	kylin_activate_i ${rootmnt}$SIGFILE ${rootmnt}$KYACTIVATION ${rootmnt}$KYINFO "$KY_ACT_CODE"  || ky_activate_retry $?
}


show_qrcode() {
	echo "输入“kylin”显示注册信息二维码，或直接回车跳过"
	sleep 1
	read  SHOW_QR_CODE

	if [ "$SHOW_QR_CODE" = "kylin" ]; then
		echo ""
		clear
		REGISTER_CODE=$(echo $1 | awk '{print $1}')
		SERIAL_CODE=$(echo $1 | awk '{print $2}')
		QR_CODE_STR="http://www.kylinos.com.cn/qywx/distro/activate?f=${SERIAL_CODE}&z=${REGISTER_CODE}"

		qrencode -t ANSIUTF8 -m 2 "${QR_CODE_STR}" 2> /dev/null && \
			echo "注册信息二维码" && \
			sleep 2 && \
			echo "请按回车键继续..." && \
			read || \
			sleep 0.1
	fi
}

ky_gen_register() {

	kylin_verify_i ${rootmnt}$SIGFILE ${rootmnt}$KYINFO || sleep 0.1
	echo ""
	echo "系统未被激活"
	echo ""

	sleep 2
	echo "请按回车键继续..."
	read

	clear
	kylin_gen_register_i ${rootmnt}$SIGFILE > /dev/null || stay_message "注册码生成失败"

	REGISTER_NO=$(kylin_gen_register_i ${rootmnt}$SIGFILE)

	show_qrcode $REGISTER_NO

	clear
	CODE_NO_HYPHEN="n"

	REGISTER_NO=$(kylin_gen_register_i ${rootmnt}$SIGFILE)
	echo $REGISTER_NO

	echo ""
	if [ $SHOW_SERIAL_NO = y ]; then
		echo "以上是注册码和序列号，请联系麒麟以获取激活码"
	else
		echo "以上是注册码，请联系麒麟以获取激活码"
	fi

	ky_activate
}

ky_verify() {
	clear
	if [ ${readonly} = y ]; then
		mount -o remount,$ROOTFS_OPTIONS,rw -t $ROOTFS_FSTYPE ${ROOT} ${rootmnt} > /dev/null 2> /dev/null
	fi

	kylin_verify_i ${rootmnt}$SIGFILE ${rootmnt}$KYINFO > /dev/null || \
		stay_message "这不是一个有效的麒麟系统"

	kylin_activation_check_i ${rootmnt}$SIGFILE ${rootmnt}$KYINFO ${rootmnt}$KYACTIVATION  > /dev/null || \
		ky_gen_register

	if [ ${readonly} = y ]; then
		sleep 1
		sync
		mount -o remount,$ROOTFS_OPTIONS,ro -t $ROOTFS_FSTYPE ${ROOT} ${rootmnt} > /dev/null 2> /dev/null
	fi
}


ky_verify

unset ROOTFS_DEVICE
unset SHOW_SERIAL_NO
unset CODE_NO_HYPHEN
